package com.personal.oa.service;

import com.personal.oa.dao.OADao;
import com.personal.oa.repository.OADocSolrRepository;
import com.personal.oa.solr.OADocSolrModel;
import com.personal.oa.until.Unitl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.util.*;

/**
 * Created by Administrator on 2017/9/13.
 */
@Service
public class OAServerImpl implements OAServer {

    private static final Logger logger = LoggerFactory.getLogger(OAServerImpl.class.getName());

    @Autowired
    private OADao oADao;
    @Autowired
    private OADocSolrRepository oADocSolrRepository;

    private OADocSolrModel oADocSolrModel;

    private List<OADocSolrModel> oadsms = new ArrayList<>();

    @Value("${num}")
    private int num;

    //oai
    List<String> oais;
    //creator
    List<String> creators;
    //subject
    List<String> subjects;
    //webaddress
    List<String> webaddresss;
    //doi
    List<String> dois;

    //language
    List<String> languages;
    //languagecn
//    List<String> languagescn;

    //source
    List<String> sources;
    //relation
    List<String> relations;
    //isbn
    List<String> isbns;
    //issn
    List<String> issns;
    //KEYWORD
    List<String> keywords;
    //FILEURL
    List<String> fileurls;


    /**
     * 将mysql数据转到solr字段
     *
     * @param startNum       开始条数
     * @param terminationNum 终止条数
     */
    @Override
    public void insertMysqlFromSolrDoc(Integer startNum, Integer terminationNum) throws FileNotFoundException {

        //记录当前的对象uuid
        String ouuid = "st";
        //记录description
        String description = null;
        //记录开始数
        int sn = startNum;
        //记录结束数
        int en = startNum;
        boolean fl = false;

        //提前清空一下，保证solr库中的都是新数据
//        oADocSolrRepository.deleteAll();

        Map<String, List> ds = new Unitl().DataMatchTransformation("dname");

        Map<String, List> las = new Unitl().DataMatchTransformation("language");
        //语言的中英文比照存储
        //Map<String,String> lascn = DataMatchTransformation("languagecn");

//        Map<String,String> ps = DataMatchTransformation("publishers"); 归置出版商
//        Map<String,String> sbj = DataMatchTransformation("subjects"); 归置学科

        while (true) {
            sn = en;
            en = en + num;
            //如何跳出循环
            if (en >= terminationNum) {
                en = terminationNum;
                fl = true;
            }

            logger.warn("从编号:" + sn + "到" + en);
            //取出指定条数的info
            long checkdbstart = System.currentTimeMillis();

            List<Map<String, Object>> ls = oADao.findSpecifiedStrip(sn, en);
            //博硕处理
//            List<Map<String, Object>> ls = doctorAndMaster(sn, en);

            if (!ls.isEmpty()) {
                long checkdbend = System.currentTimeMillis();
                logger.warn("查询数据耗时:" + (checkdbend - checkdbstart));
                logger.warn("开始处理数据......");

                String ovalue = "";//oa对象类型为博硕时，记录学位信息的中间变量
                boolean lc = true;

                for (Map<String, Object> oa : ls) {
                    //数据库中的字段UUID
                    String fielduid = oa.get("tfuuid").toString();
                    //数据库中的对象uuid
                    String dbouuid = oa.get("obuuid").toString();
                    //数据库中的内容字段
                    String con = oa.get("te_content").toString();
                    //数据库中的类型字段
                    String typefiled = oa.get("tb_typeid").toString();

                    if (!ouuid.equals(dbouuid)) {//对象ID不等的时候继续
                        if (!"st".equals(ouuid)) {//对象ID不等于初始化的时候继续
                            oADocSolrModel.setOai(oais);
                            oADocSolrModel.setCreator(creators);
                            oADocSolrModel.setSubject(subjects);
                            oADocSolrModel.setDescription(description);
                            description = null;
                            oADocSolrModel.setWebaddress(webaddresss);
                            oADocSolrModel.setDoi(dois);
                            if (languages.size() == 0) {
                                languages.add("English");
                                oADocSolrModel.setLanguage(languages);
                            } else {
                                oADocSolrModel.setLanguage(languages);
                            }
//                        oADocSolrModel.setLanguagecn(languagescn);

                            oADocSolrModel.setSource(sources);
                            oADocSolrModel.setIsbn(isbns);
                            oADocSolrModel.setIssn(issns);
                            oADocSolrModel.setKetwords(keywords);
                            oADocSolrModel.setRelation(relations);
                            oADocSolrModel.setFileurl(fileurls);

                            //加入对象类型
                            if ("3".equals(typefiled)) {
                                if ("".equals(ovalue)) {
                                    oADocSolrModel.setOatypecn("32");
                                } else {
                                    switch (ovalue) {
                                        case "Bachelor"://学士
                                            oADocSolrModel.setOatypecn("31");
                                            ovalue = "";
                                            break;
                                        case "Master"://硕士
                                            oADocSolrModel.setOatypecn("32");
                                            ovalue = "";
                                            break;
                                        case "Doctor"://博士
                                            oADocSolrModel.setOatypecn("33");
                                            ovalue = "";
                                            break;
                                    }
                                }
                            } else {
                                oADocSolrModel.setOatypecn(typefiled);
                            }

                            oadsms.add(oADocSolrModel);
                        }

                        ouuid = dbouuid;
                        oADocSolrModel = new OADocSolrModel();
                        //加入对象id
                        oADocSolrModel.setId(dbouuid);
//                    switch (typefiled) {
//                        case "1":
//                            oADocSolrModel.setOatypecn("预印本");
////                            oADocSolrModel.setOatype("Preprint");
//                            break;
//                        case "2":
//                            oADocSolrModel.setOatypecn("期刊");
////                            oADocSolrModel.setOatype("Periodical");
//                            break;
//                        case "3":
//                            oADocSolrModel.setOatypecn("博硕");
////                            oADocSolrModel.setOatype("Doctor and Master");
//                            break;
//                        case "4":
//                            oADocSolrModel.setOatypecn("书籍");
////                            oADocSolrModel.setOatype("Book");
//                            break;
//                    }
                        oais = new ArrayList<>();
                        creators = new ArrayList<>();
                        subjects = new ArrayList<>();
                        webaddresss = new ArrayList<>();
                        dois = new ArrayList<>();

                        languages = new ArrayList<>();
//                    languagescn = new ArrayList<>();
                        lc = true;

                        sources = new ArrayList<>();
                        isbns = new ArrayList<>();
                        issns = new ArrayList<>();
                        keywords = new ArrayList<>();
                        relations = new ArrayList<>();
                        fileurls = new ArrayList<>();

                    }

                    switch (fielduid) {
                        //oai
                        case "e37bd41d-8df2-11e7-9753-1c1b0d1cb748":
                            if (con.startsWith("oai:")) {
                                oais.add(con.substring(4));
                            } else {
                                oais.add(con);
                            }
                            break;
                        //datestamp 更新时间
                        case "06f092fd-8df3-11e7-9753-1c1b0d1cb748":
                            Date dtc = new Unitl().convertDate(con, dbouuid, logger);
                            if (dtc != null) {
                                oADocSolrModel.setDatestamp(dtc);
                                //datestampyear
                                oADocSolrModel.setDatestampyear(dtc.getYear() + 1900);
                            }
                            break;
                        //title 标题
                        case "51bd9b54-8df4-11e7-9753-1c1b0d1cb748":
                            oADocSolrModel.setTitle(StringEscapeUtils.unescapeHtml4(con));
                            break;
                        //creator 作者
                        case "56245e05-8df4-11e7-9753-1c1b0d1cb748":
                            creators.add(con);
                            break;
                        //subject 学科
                        case "5a767d35-8df4-11e7-9753-1c1b0d1cb748":
                            String[] sbs = con.toLowerCase().split(";");
                            for (String ss : sbs) {
                                if (StringUtils.startsWithIgnoreCase(ss,"DOAJ:")) {
                                    subjects.add(ss.substring(5).toLowerCase().trim());
                                } else {
                                    subjects.add(ss.toLowerCase().trim());
                                }
                            }
                            break;
                        //description 描述
                        case "5ea386c7-8df4-11e7-9753-1c1b0d1cb748":
                            if (description == null) {
                                description = StringEscapeUtils.unescapeHtml4(con);
                            } else {
                                description = description + "\n" + StringEscapeUtils.unescapeHtml4(con);
                            }
                            break;
                        //creattime 创建时间
                        case "642bf276-8df4-11e7-9753-1c1b0d1cb748":
                            Date ctc = new Unitl().convertDate(con, dbouuid, logger);
                            if (ctc != null) {
                                if (ctc.before(new Date())) {//表示ctc小于当期时间
                                    oADocSolrModel.setCreattime(ctc);
                                    //creattimeyear
                                    oADocSolrModel.setCreattimeyear(ctc.getYear() + 1900);
                                }
                            }
                            break;
                        //type 类型(不是oa的分类)
                        case "685b95b6-8df4-11e7-9753-1c1b0d1cb748":
                            oADocSolrModel.setType(con);
                            break;
                        //学位
                        case "76f6dfed-a25b-11e7-a865-1c1b0d1cb748":
                            boolean dc = true;
                            String[] myList = {"Doctor", "Master", "Bachelor"};
                            for (String str : myList) {
                                List<Map<String, String>> dls = ds.get(str);
                                for (Map<String, String> dms : dls) {
                                    if (con.compareToIgnoreCase(dms.get("name")) == 0) {
                                        ovalue = str;//赋给博硕类型的中间变量
                                        //dbelongsto (博、硕、学士的分类)
                                        oADocSolrModel.setDbelongsto(str);
                                        oADocSolrModel.setDname(con);
                                        dc = false;
                                        break;
                                    }
                                    ;
                                }
                                if (!dc) {
                                    break;
                                }
                            }
                            if (dc) { //没有可辨识的分类信息
                                //dbelongsto (博、硕、学士的分类)
                                oADocSolrModel.setDbelongsto(con);//记录一下不可辨识的数据库数据
                                oADocSolrModel.setDname("other");
//                            oADocSolrModel.setDbelongstocn(dnameCheck(ds.get("other")));
                            }
                            break;
                        //webaddress 网址
                        case "6d8fcfb8-8df4-11e7-9753-1c1b0d1cb748":
                            webaddresss.add(StringEscapeUtils.unescapeHtml4(con));
                            break;
                        //doi
                        case "77ab2c86-8df4-11e7-9753-1c1b0d1cb748":
                            if (con.startsWith("doi:")) {
                                dois.add(con.substring(4));
                            } else {
                                dois.add(con);
                            }
                            break;
                        //publisher 出版社
                        case "e0f5da25-9781-11e7-aea2-1c1b0d1cb748":
                            oADocSolrModel.setPublisher(con);
                            break;
                        //language 语言
                        case "f16d02d9-9781-11e7-aea2-1c1b0d1cb748":
                            for (String str : las.keySet()) {
                                List<Map<String, String>> lls = las.get(str);
                                for (Map<String, String> lms : lls) {
                                    if (con.compareToIgnoreCase(lms.get("name")) == 0) {
                                        if (!languages.contains(str)) {
                                            languages.add(str);
//                                          languagescn.add(lascn.get(las.get(str)));
                                            lc = false;
                                        }

                                    }
                                    ;
                                }
                            }
                            if (lc) {//存在语种但是不被记录的归于英语
                                if (!languages.contains("English")) {
                                    languages.add("English");
                                }
                            }
                            break;
                        //source 资源
                        case "f723893d-9781-11e7-aea2-1c1b0d1cb748":
                            sources.add(con);
                            String[] re = con.split(",");
                            oADocSolrModel.setJournalname(re[0]);

                            String rc = new Unitl().matchingJournal(", (.*)", con);
                            try {
                                oADocSolrModel.setVol(new Unitl().matchingJournal("Vol (.*?)(,| )", rc));
                                oADocSolrModel.setIss(new Unitl().matchingJournal("Iss (.*?)(,| )", rc));
                                oADocSolrModel.setPp(new Unitl().matchingJournal("P?p (.*?)( |$)", re[re.length - 1]));
                            } catch (NullPointerException e) {
                                logger.warn("ID:" + dbouuid + "==无卷、期、页数据");
                            }
                            break;
                        //relation 关系
                        case "11984f02-9782-11e7-aea2-1c1b0d1cb748":
                            relations.add(con);
                            break;
                        //ISBN
                        case "81f7c233-a25b-11e7-a865-1c1b0d1cb748":
                            isbns.add(con);
                            break;
                        //ISSN
                        case "ff8ba074-9781-11e7-aea2-1c1b0d1cb748":
                            issns.add(con);
                            break;
                        //KEYWORDS 关键词
                        case "71c9542c-a27a-11e7-a865-1c1b0d1cb748":
                            keywords.add(con.toLowerCase());
                            break;

                        //UNIVERSITY 大学
                        case "d97f9f28-a25b-11e7-a865-1c1b0d1cb748":
                            oADocSolrModel.setUniversity(Arrays.asList(con.split("/")));
                            break;
//                    //来源库,作为记录大学数据存储的资源库
//                    case "a4d9d894-eb76-11e7-93e0-9cb654b27c79":
//                        svalue = con;
//                        break;

                        //COUNTRY 国家
                        case "e132a425-a25b-11e7-a865-1c1b0d1cb748":
                            oADocSolrModel.setCountry(con);
                            break;
                        //FILEURL 文件地址
                        case "e5cdce70-a25b-11e7-a865-1c1b0d1cb748":
                            fileurls.add(con);
                            break;

                    }
                }
                logger.warn("结束处理数据......开始solr录入");
                oADocSolrRepository.save(oadsms);
                logger.warn("结束solr录入\n");
                oadsms.clear();
            }

            if (fl) {
                break;
            }

        }
    }

    //博硕返回指定条数的数据
    public List<Map<String, Object>> doctorAndMaster(Integer startNum, Integer endNum) {
        List<Map<String, Object>> fruits = new ArrayList<>();
        List<String> ouo = oADao.oa_university_oai(startNum, endNum);
        for (String str : ouo) {
            List<Map<String, Object>> ob = oADao.tb_info_doctor_master(str);
            for (Map<String, Object> oa : ob) {
                fruits.add(oa);
            }
        }
        return fruits;
    }

}
